package com.hzvdvmc.autosale.setting.ui;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;

import com.hzvdvmc.autosale.R;
import com.hzvdvmc.autosale.base.ActionbarActivity;
import com.hzvdvmc.autosale.common.OnItemClickListener;
import com.hzvdvmc.autosale.constant.GlobleCache;
import com.hzvdvmc.autosale.constant.SpKey;
import com.hzvdvmc.autosale.sale.ui.InputDialog;
import com.hzvdvmc.autosale.setting.adapter.AboutRvAdapter;
import com.hzvdvmc.autosale.setting.bean.AboutSettingEnum;
import com.hzvdvmc.autosale.setting.bean.AboutStateBean;
import com.hzvdvmc.autosale.setting.bean.RoleEnum;
import com.hzvdvmc.autosale.socket.HttpConstants;
import com.hzvdvmc.autosale.util.MachineUtil;
import com.hzvdvmc.autosale.util.NetworkUtils;
import com.hzvdvmc.autosale.util.SPUtils;
import com.hzvdvmc.autosale.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import android_serialport_api.SeriaPortClient;
import butterknife.BindView;
import butterknife.ButterKnife;

public class AboutActivity extends ActionbarActivity {

    @BindView(R.id.rv_info_list)
    RecyclerView rvInfoList;

    private AboutRvAdapter mAdapter;
    private List<AboutStateBean> dataList = new ArrayList<>();
    private RoleEnum role;

    public static void startMe(Context context, RoleEnum role) {
        Intent intent = new Intent(context, AboutActivity.class);
        intent.putExtra("role", role);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_about);
        ButterKnife.bind(this);
        setCustomeActiorBar("关于设备");
        parseIntent();
        initRecyclerView();
        loadDataFromSp();
    }

    private void parseIntent() {
        role = (RoleEnum) getIntent().getSerializableExtra("role");
    }

    private void loadDataFromSp() {
        String signState = "";
        if (GlobleCache.isSign) {
            signState = "已签到";
        } else {
            signState = "未签到";
        }
        String netWorkState = "网络未连接";
        if (NetworkUtils.isConnected()) {
            netWorkState = "网络正常";
        }
        String machineNO = MachineUtil.getDeviceNO();

        String ip = HttpConstants.getScoketIP();
        String port = HttpConstants.getSocketPort();
        String httpIP = HttpConstants.getHttpIP();
        String httpPort = HttpConstants.getHttpPort();
        String tel = SPUtils.getInstance().getString(SpKey.TEL);
//        int borate = SPUtils.getInstance().getInt(SpKey.BO_RATE, SeriaPortClient.DEFAULT_BAUDRATE);

        dataList.clear();
        dataList.add(new AboutStateBean(AboutSettingEnum.net_state.getName(), netWorkState));
        dataList.add(new AboutStateBean(AboutSettingEnum.sign_state.getName(), signState));
        dataList.add(new AboutStateBean(AboutSettingEnum.machine_no.getName(), machineNO));
        dataList.add(new AboutStateBean(AboutSettingEnum.socket_ip.getName(), ip));
        dataList.add(new AboutStateBean(AboutSettingEnum.socket_port.getName(), port));
        dataList.add(new AboutStateBean(AboutSettingEnum.http_ip.getName(), httpIP));
        dataList.add(new AboutStateBean(AboutSettingEnum.http_port.getName(), httpPort));
        dataList.add(new AboutStateBean(AboutSettingEnum.phone.getName(), tel));
        dataList.add(new AboutStateBean(AboutSettingEnum.version.getName(), getAppVersionName(this)));
//        dataList.add(new AboutStateBean(AboutSettingEnum.borate.getName(), borate + ""));
//        dataList.add(new AboutStateBean(AboutSettingEnum.serial.getName(), ""));
        mAdapter.notifyDataSetChanged();

    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);
            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }


    private void initRecyclerView() {
        rvInfoList.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new AboutRvAdapter(dataList);
        rvInfoList.setAdapter(mAdapter);
        //权限限制
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onClick(View v, int position) {
                if (!hasRolePermission()) {
                    ToastUtils.showShort("无操作权限");
                    return;
                }
                String key = dataList.get(position).getKey();
                if (key.equals(AboutSettingEnum.machine_no.getName())) {
                    showInputDialog(InputType.TYPE_CLASS_TEXT, AboutSettingEnum.machine_no);
                } else if (key.equals(AboutSettingEnum.socket_ip.getName())) {
                    showInputDialog(InputType.TYPE_CLASS_TEXT, AboutSettingEnum.socket_ip);
                } else if (key.equals(AboutSettingEnum.socket_port.getName())) {
                    showInputDialog(InputType.TYPE_CLASS_TEXT, AboutSettingEnum.socket_port);
                } else if (key.equals(AboutSettingEnum.http_ip.getName())) {
                    showInputDialog(InputType.TYPE_CLASS_TEXT, AboutSettingEnum.http_ip);
                } else if (key.equals(AboutSettingEnum.http_port.getName())) {
                    showInputDialog(InputType.TYPE_CLASS_TEXT, AboutSettingEnum.http_port);
                } else if (key.equals(AboutSettingEnum.phone.getName())) {
                    showInputDialog(InputType.TYPE_CLASS_TEXT, AboutSettingEnum.phone);
                } else if (key.equals(AboutSettingEnum.borate.getName())) {
                    showInputDialog(InputType.TYPE_CLASS_NUMBER, AboutSettingEnum.borate);
                } else if (key.equals(AboutSettingEnum.serial.getName())) {
                    startActivity(new Intent(AboutActivity.this, SerialAddressActivity.class));
                }
            }


        });
    }

    private boolean hasRolePermission() {
        if (role != null && role.getPermission() >= RoleEnum.Factory.getPermission()) {
            return true;
        }
        return false;
    }

    private void showInputDialog(int inputType, final AboutSettingEnum settingEnum) {
        final InputDialog dialog = new InputDialog(this, R.style.MyDialog, inputType);
        dialog.show();
        dialog.setCurrentValue(dataList.get(settingEnum.getValue()).getName());
        dialog.setOkOnClickListenter(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String inputContent = dialog.getInputContent();

                if (TextUtils.isEmpty(inputContent)) {
                    ToastUtils.showShort("输入不能为空");
                    return;
                }

                if (settingEnum == AboutSettingEnum.machine_no && inputContent.length() < 12) {
                    //设备号
                    ToastUtils.showShort("设备号必须为12位");
                    return;
                }


                saveData(inputContent, settingEnum);
                dialog.dismiss();
            }
        });
        dialog.setCancelOnClickListenre(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setTitle(settingEnum.getName());
    }

    private void saveData(String data, final AboutSettingEnum settingEnum) {
        switch (settingEnum) {
            case machine_no:
                SPUtils.getInstance().put(SpKey.MACHINE_NO, data);
                break;
            case socket_ip:
                HttpConstants.setSocketIP(data);
                break;
            case socket_port:
                HttpConstants.setSocketPort(data);
                break;
            case http_ip:
                HttpConstants.setHttpIP(data);
                break;
            case http_port:
                HttpConstants.setHttpPort(data);
                break;
            case phone:
                SPUtils.getInstance().put(SpKey.TEL, data);
                break;
            case borate:
                SPUtils.getInstance().put(SpKey.BO_RATE, Integer.parseInt(data));
                break;
        }
        loadDataFromSp();
    }

    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }
}
